import { Injectable } from '@nestjs/common';
import { DrizzleService } from '../../db/drizzle.service';
import { loginLogs } from '../../db/schema';
import { CreateLoginLogDto, PageQueryDto } from './dto/login-log.schema';
import { and, eq, gte, lte, like, sql } from 'drizzle-orm';

@Injectable()
export class LoginLogService {
  constructor(private readonly drizzle: DrizzleService) { }

  /**
   * 创建登录日志
   */
  async create(createLoginLogDto: CreateLoginLogDto) {
    return await this.drizzle.db.insert(loginLogs).values(createLoginLogDto);
  }

  /**
   * 分页查询登录日志
   */
  async findByPage(query: PageQueryDto) {
    const { pageNum, pageSize, userName, status, startTime, endTime } = query;
    const offset = (pageNum - 1) * pageSize;

    // 构建查询条件
    let whereConditions = [];
    if (userName) {
      whereConditions.push(like(loginLogs.userName, `%${userName}%`));
    }
    if (status) {
      whereConditions.push(eq(loginLogs.status, status));
    }
    if (startTime) {
      whereConditions.push(gte(loginLogs.loginTime, new Date(startTime)));
    }
    if (endTime) {
      whereConditions.push(lte(loginLogs.loginTime, new Date(endTime)));
    }

    // 执行计数查询
    const countQuery = whereConditions.length > 0
      ? this.drizzle.db
        .select({ count: sql`COUNT(*)` })
        .from(loginLogs)
        .where(and(...whereConditions))
      : this.drizzle.db
        .select({ count: sql`COUNT(*)` })
        .from(loginLogs);

    const countResult = await countQuery;
    const total = Number(countResult[0]?.count || '0');

    // 执行数据查询
    const dataQuery = whereConditions.length > 0
      ? this.drizzle.db
        .select()
        .from(loginLogs)
        .where(and(...whereConditions))
        .limit(pageSize)
        .offset(offset)
        .orderBy(sql`${loginLogs.loginTime} DESC`) // 按登录时间降序排列
      : this.drizzle.db
        .select()
        .from(loginLogs)
        .limit(pageSize)
        .offset(offset)
        .orderBy(sql`${loginLogs.loginTime} DESC`);

    const rows = await dataQuery;

    return {
      rows,
      total,
      pageNum,
      pageSize,
    };
  }

  /**
   * 清空登录日志
   */
  async clear() {
    return await this.drizzle.db.delete(loginLogs);
  }

  /**
   * 删除登录日志
   */
  async remove(ids: number[]) {
    return await this.drizzle.db
      .delete(loginLogs)
      .where(sql`${loginLogs.infoId} IN (${ids.join(',')})`);
  }
} 